package team.scau.laboratory_repair.web.pc;

import com.querydsl.core.QueryResults;
import lombok.extern.apachecommons.CommonsLog;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import team.scau.laboratory_repair.common.base.BaseController;
import team.scau.laboratory_repair.common.json.JqGridResult;
import team.scau.laboratory_repair.common.json.PoToDto;
import team.scau.laboratory_repair.modules.dto.RecordDto;
import team.scau.laboratory_repair.modules.po.*;
import team.scau.laboratory_repair.service.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: ${todo}
 * @Author: wxz1997
 * @Date 18-7-27下午1:33
 */
@RequestMapping("/pc/biz/record")
@Controller
@CommonsLog
public class RecordController extends BaseController {

    @Autowired
    private RecordService recordService;

    @Autowired
    private RepairClassifyService repairClassifyService;

    @Autowired
    private RecordPhotoService recordPhotoService;

    @Autowired
    private AreaService areaService;

    @Autowired
    private PoToDto poToDto;

    @ModelAttribute("record")
    public Record get(@RequestParam(required = false, value = "id") Long id) throws Exception {
        if (id != null && id > 0) {
            return recordService.findById(id);
        } else {
            return new Record();
        }
    }

    @RequiresPermissions("biz:record:list")
    @GetMapping(value = "/list", produces = "text/html;charset=utf-8")
    public String list(Model model) throws Exception{
        List<Area> areas = areaService.listOrByExample(null,null).getResults();
        Map<Long, String> areaMap = new HashMap<>();
        for(Area area : areas){
            areaMap.put(area.getId(), area.getName());
        }
        List<RepairClassify> classifies = repairClassifyService.findAll();
        Map<Long, String> classifyMap = new HashMap<>();
        for(RepairClassify classify : classifies){
            classifyMap.put(classify.getId(), classify.getName());
        }
        model.addAttribute("areas", areas);
        model.addAttribute("areaMap", areaMap);
        model.addAttribute("classifies", classifies);
        model.addAttribute("classifyMap", classifyMap);
        return "/pc/biz/record/list";
    }

    @ResponseBody
    @RequiresPermissions("biz:record:list")
    @RequestMapping(value = "/list.json", produces = "application/json;charset=utf-8")
    public JqGridResult list(@ModelAttribute Record record) throws Exception {
        QueryResults<Record> queryResults = recordService.listOrByExample(record, getPage(QRecord.class));
        List<RecordDto> records = poToDto.recordList(queryResults.getResults());
        return new JqGridResult(queryResults, records);
    }

//    @RequiresPermissions("biz:record:process")
//    @GetMapping(value = "/process", produces = "text/html;charset=utf-8")
//    public String process(Model model, @ModelAttribute Record record) throws Exception{
//        model.addAttribute("record", record);
//        return "/pc/biz/record/process";
//    }
//
//    @ResponseBody
//    @RequiresPermissions("biz:record:process")
//    @RequestMapping(value = "/process.json", produces = "application/json;charset=utf-8")
//    public JqGridResult process(@ModelAttribute("record") Record record) throws Exception {
//        QueryResults<RecordSubscription> queryResults = repairClassifyService.listOrByExample(getPage(QRecordSubscription.class), record);
//        List<RecordSubscriptionDto> records = poToDto.recordSubscriptionList(queryResults.getResults());
//        return new JqGridResult(queryResults, records);
//    }

    @RequiresPermissions("biz:record:list")
    @GetMapping(value = "/view", produces = "text/html;charset=utf-8")
    public String view(@ModelAttribute("record") Record record, Model model) throws Exception{
        model.addAttribute("record",record);
        List<Area> areas = areaService.listOrByExample(null,null).getResults();
        Map<Long, String> areaMap = new HashMap<>();
        for(Area area : areas){
            areaMap.put(area.getId(), area.getName());
        }
        List<RepairClassify> classifies = repairClassifyService.findAll();
        Map<Long, String> classifyMap = new HashMap<>();
        for(RepairClassify classify : classifies){
            classifyMap.put(classify.getId(), classify.getName());
        }
        List<RecordPhoto> photos = recordPhotoService.listByRecordId(record.getId());
        if(photos!= null && photos.size()>0){
            model.addAttribute("photos", photos);
        }
        model.addAttribute("areas", areas);
        model.addAttribute("areaMap", areaMap);
        model.addAttribute("classifies", classifies);
        model.addAttribute("classifyMap", classifyMap);
        return "/pc/biz/record/view";
    }

    @RequiresPermissions("biz:record:edit")
    @GetMapping(value = "/edit", produces = "text/html;charset=utf-8")
    public String edit(@ModelAttribute("record") Record record, Model model) throws Exception{
        model.addAttribute("record",record);
        List<Area> areas = areaService.listOrByExample(null,null).getResults();
        Map<Long, String> areaMap = new HashMap<>();
        for(Area area : areas){
            areaMap.put(area.getId(), area.getName());
        }
        List<RepairClassify> classifies = repairClassifyService.findAll();
        Map<Long, String> classifyMap = new HashMap<>();
        for(RepairClassify classify : classifies){
            classifyMap.put(classify.getId(), classify.getName());
        }
        model.addAttribute("areas", areas);
        model.addAttribute("areaMap", areaMap);
        model.addAttribute("classifies", classifies);
        model.addAttribute("classifyMap", classifyMap);
        // TODO 图片url传出
//        model.addAttribute("url","http://p4.qhimg.com/dr/100__/t01cbdfee083acb4039.png");
        return "/pc/biz/record/edit";
    }
    @RequiresPermissions(value = "biz:record:edit", logical = Logical.OR)
    @PostMapping(value = "/edit", produces = "application/json;charset=utf-8")
    @ResponseBody
    public Map<String,Object> edit(@ModelAttribute Record record
            // TODO 图片url接收
            , @RequestParam("url")String url){
        Map<String,Object> result = new HashMap<>();
        try {
            recordService.save(record);
            RecordPhoto photo = RecordPhoto.builder().url(url).recordId(record.getId()).build();
            recordPhotoService.save(photo);
            result.put("status",200);
            result.put("msg","订单信息保存成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage(), e);
            result.put("status",500);
            result.put("msg","订单信息保存失败");
        }
        return result;
    }

    @RequiresPermissions("biz:record:edit")
    @PostMapping(value = "/editClassify", produces = "application/json;charset=utf-8")
    @ResponseBody
    public Map<Long,String> editClassify(Long areaId){
        List<RepairClassify> results = repairClassifyService.listOrByExample(RepairClassify.builder().locationId(areaId).build(), getPage(QRepairClassify.class)).getResults();
        HashMap<Long,String> hashMap=new HashMap<>();
        for(RepairClassify repairClassify:results){
            hashMap.put(repairClassify.getId(),repairClassify.getName());
        }
        return hashMap;
    }


    @RequiresPermissions("biz:record:delete")
    @PostMapping(value = "/delete", produces = "application/json;charset=utf-8")
    @ResponseBody
    public Map<String,Object> delete(Long id){
        Map<String,Object> result = new HashMap<>();
        try {
            if(id != null && id > 0){
                recordService.deleteById(id);
                result.put("status",200);
                result.put("msg","删除订单成功");
            }else {
                result.put("status",500);
                result.put("msg","请选择删除的订单");
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage(), e);
            result.put("status",500);
            result.put("msg","删除订单失败");
        }
        return result;
    }
}
